/**
 *@description 用户登录后开启websock请求
 * */
import store from '../../store'
import { Notification } from 'element-ui';
import db from '../../../datastore'
import mqtt from 'mqtt'

var client
const options = {
    reconnectPeriod: 1000, // 1000毫秒，两次重新连接之间的间隔
    connectTimeout: 40000, // 40 * 1000毫秒，等待收到CONNACK的时间
    clientId: 'pc' + Math.random().toString(16).substr(2, 8),
    username: "",
    password: "",
    clean: true
}

let ws = null // websock
let heart = null // 心跳包定时器id
let isWrong = false // 标记是否密码错误
let isError = false // 标记是否连接错误
var temp = new Array(); // 重连数组

// 将重连信息移除
function removeTemp (obj) {
	console.log("重连信息")
  var id = obj.id;
  //将请求记录从 temp 中去掉
  for (var key in temp) {
    if (id == temp[key].id) {
      console.log("移除:" + temp[key].id);
      temp.slice(key, 1);
      break;
    }
  }
}

// 发送WebSocket请求
function wsSend (param, content) {
    console.log('client', client)
    client.publish(param, content, {qos: 2})
}

// 接收WebSocket返回信息
function wsOnMessage(topic, data) {
    console.log('topiclen', (topic.split('/')).length, data)
    let num = (topic.split('/')).length-1
    if (num == 2) {
        store.dispatch('user/getChatList', data)
    } else {
        let _data = JSON.parse(data)
        store.dispatch('user/updateChatList', _data)
    }
    // else if(num == 0) {
    //     console.log('data0:', data)
    //     // let data = message.toString()
    //     if (data.indexOf(';') != -1) {
    //         let dataArr = data.split(';')
    //         dataArr.pop()
    //         let num = Math.floor((Math.random()*dataArr.length));
    //         store.dispatch('user/updateKid', num)
    //     } else {
    //         store.dispatch('user/updateKid', data)
    //     }
    //     // console.log(dataArr)
    // } 
}

// WebSocket关闭回调
function wsClose () {
  if (ws && store.getters.trade) {
    store.dispatch('user/changeTradeStatu', false)
    window.clearInterval(heart)
    isError = false
    heart = null
      client.end()
  } else {
    // eslint-disable-next-line prefer-promise-reject-errors
    console.log('websock对象不存在或未创建')
  }
}

function initkehuWs () {
    let loginData = store.getters.userInfo2;
    
    options.username = loginData.data.uid + '_pc'
    options.password = loginData.data.token
    // 获取url
    let nodeList = db
        .read()
        .get("trades.lineNode")
        .value();
    let loginUrl = nodeList.filter(v => v.selected)[0];
    client = mqtt.connect(loginUrl.node, options);
    client.on('connect', (e) => {
        let _chatList = localStorage.getItem('chatList') ? JSON.parse(localStorage.getItem('chatList')) : []
        // _chatList = JSON.parse(arr)
        console.log('_chatList', _chatList)
        if (_chatList) {
            store.dispatch('user/updateChatList0', _chatList)
        }
        // store.dispatch('user/updateChatList0', _chatList ? _chatList : [])
        // 客户聊天接收信息
        // client.subscribe('customerSerOnline', (error) => {
        //     if (!error) {
        //         console.log('客服列表订阅成功')
        //     } else {
        //         console.log('客服列表订阅失败')
        //     }
        // })
        client.subscribe(`chating/customerSer/${store.getters.uid}/${store.getters.kid}`, {qos: 2},  (error) => {
            if (!error) { // 接收消息 chating/customerSer/用户id
                console.log('客户接收消息订阅成功', `chating/customerSer/${store.getters.uid}/${store.getters.kid}`)

            } else {
                console.log('客户接收消息订阅失败')
            }
        })
        // client.subscribe(`chating/hisCustomerSer/${store.getters.uid}`, {qos: 2}, (error) => {
        //     if (!error) { // 历史数据 chating/hisCustomerSer/用户id
        //         console.log('客户接收历史消息消息订阅成功', `chating/hisCustomerSer/${store.getters.uid}`)
        //     } else {
        //         console.log('客户接收历史消息订阅失败')
        //     }
        // })
       
    })
    
    // 接收消息处理
    client.on('message', (topic, message) => {
        console.log('接收消息', topic, message)
        wsOnMessage(topic, message.toString())
    })
    // 断开发起重连
    client.on('reconnect', (error) => {
        console.log('正在重连:', error)
    })
    // 链接异常处理
    client.on('error', (error) => {
        console.log('连接失败:', error)
    })
}

export {
  wsClose,
  initkehuWs,
  wsSend,
  wsOnMessage
}
